package ch.bfh.cmdh.thinkerforge.weatherstation.model.temperature;

import java.io.IOException;
import java.net.UnknownHostException;

import ch.bfh.cmdh.thinkerforge.weatherstation.controller.WeatherStationController;
import ch.bfh.cmdh.thinkerforge.weatherstation.model.WeatherStationSensor;

import com.tinkerforge.AlreadyConnectedException;
import com.tinkerforge.BrickletTemperature;
import com.tinkerforge.BrickletTemperature.TemperatureListener;
import com.tinkerforge.IPConnection;
import com.tinkerforge.NotConnectedException;
import com.tinkerforge.TimeoutException;

public class TemperatureSensor implements WeatherStationSensor {

    public static final String TEMPERATURE_KEY = "tempreature";
    private static final String TEMPERATURE_SENSOR_UID = "dz1";

    private WeatherStationController controller;
    private IPConnection ipConnection;
    private BrickletTemperature brickletTemperature;

    public TemperatureSensor(WeatherStationController controller) {
        this.controller = controller;
        this.ipConnection = new IPConnection();
        this.brickletTemperature = new BrickletTemperature(TEMPERATURE_SENSOR_UID, ipConnection);
        this.brickletTemperature.addTemperatureListener(new TempListener());
    }

    @Override
    public void connect() throws UnknownHostException, AlreadyConnectedException, IOException, TimeoutException,
            NotConnectedException {
        ipConnection.connect(WeatherStationController.HOST, WeatherStationController.PORT);
        this.brickletTemperature.setTemperatureCallbackPeriod(WeatherStationController.CALLBACK_PERIOD);
    }

    @Override
    public void disconnect() throws NotConnectedException {
        ipConnection.disconnect();

    }
    
    private class TempListener implements TemperatureListener{

        @Override
        public void temperature(short temperature) {
            TemperatureSensor.this.controller.updateGUI(TEMPERATURE_KEY, temperature);
            
        }
        
    }

}
